#coding: utf-8
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
from django.core.urlresolvers import reverse
from django.utils.html import urlize
# import cgi
# from loginza_auth import update_loginza_userinfo

class UserProfile(models.Model):
    # This is the only required field
    user = models.OneToOneField(User, parent_link = True, related_name="user")
    photo = models.CharField(u'Фото', max_length = 1024)
    nickname = models.CharField(u'Ник', max_length = 128)
    jabber = models.CharField(u'Jabber', max_length = 128, null=True, blank=True)
    show_avatar = models.BooleanField(u'Показывать аватар', default=True)
    def __unicode__(self):
        if self.user.first_name!='' or self.user.last_name!='':
            return u"{0} {1}".format(self.user.first_name, self.user.last_name) if self.user.last_name!='' else self.user.first_name
        elif self.nickname: return self.nickname
        else: return self.user.username            
    def save(self):
        self.update_loginza_userinfo()
        if not self.jabber and self.user.email != 'user@loginza':
            self.jabber = self.user.email
        super(UserProfile, self).save()

    def update_loginza_userinfo(self, user_map = None):
        from loginza.models import UserMap
        import simplejson as json

        print('update_loginza_userinfo')
        if user_map == None:
            try:
                user_map = UserMap.objects.get(user = self.user)
            except Exception as e: 
                print "cant get usermap for uid ", self.user.id, "with error:", e

        if not user_map: return False

        soc_info = json.loads(user_map.identity.data)
        name_info = soc_info.get('name', False)

        first_name, last_name, full_name = None, None, None
        
        if name_info:
            first_name = name_info.get('first_name', None)
            last_name = name_info.get('last_name', None)
            full_name = name_info.get('full_name', None)

        nickname = soc_info.get('nickname', None)
        photo = soc_info.get('photo', None)
        email = soc_info.get('email', None)

        #request.session['user_profile'] = None

        profile_changed = False
        user_changed = False

        if nickname: self.nickname = nickname
        # это делает сама loginza
        #if email:
        #    self.user.email = email
        #    user_changed = True
        if first_name:
            self.user.first_name = first_name
            if last_name: 
                self.user.last_name = last_name
            user_changed = True
        else:
            if full_name: 
                self.user.first_name = full_name
                user_changed = True
        if photo:
            self.photo = photo
            profile_changed = True
        if nickname:
            self.nickname = nickname
            profile_changed = True
        
        if user_changed:
            #print u"saving user.first_name user.last_name: {0} {1}".format(self.user.first_name, self.user.last_name)
            self.user.save()
        else:
            print "user not changed"

        if profile_changed: print "profile changed"
        else: print "profile not changed"

